
# from read_cfg_txt import load_cgxh_cfg
import os, time
import ast
import numpy as np
from common.utils import *
from midea_common.ocrhelper import *

def get_pas(path_cfg_cpxh):
    out = []
    pa = path_cfg_cpxh
    while '\\' in pa or '/' in pa:
        pa = os.path.split(pa)[0]
        pa = pa.strip('\\/')
        if pa not in out:
            out.append(pa)
        else:
            break

    return out

def load_cgxh_cfg(path_cfg_cpxh):
    ret_json = {}
    #path_cfg_cpxh = "D:/data/model_save/pj_005_midea_hefei_230710/cpxh_cfg_file/peifang_write.txt"
    path_cfg_cpxh = path_cfg_cpxh.replace('midea', '')
    if not os.path.exists(path_cfg_cpxh):
        papa = get_pas(path_cfg_cpxh)
        path_cfg_cpxh = find_file(os.path.split(path_cfg_cpxh)[1], papa)
    if os.path.exists(path_cfg_cpxh):
        #print(f"file is exists")
        lines = None
        try:
            with open(path_cfg_cpxh, 'r', encoding='utf8') as f_cfg:
                lines = f_cfg.readlines()
                # print(f"{lines}")
            if lines is not None:
                for line in lines:
                    # print(f"ori-line:{line}")
                    line = line.strip().replace("，",",").strip(",")
                    # print(f"new-line:{line}")
                    res_a = ast.literal_eval(line)  # 强转 数据类型
                    # print(f"[type]:{type(res_a)}, res_a:{res_a}")
                    if isinstance(res_a, dict):
                        for key, val in res_a.items():
                            if key not in ret_json.keys():
                                ret_json[key] = val
                            else:
                                print(f"[err]  [read_cdf]  exists same chxh:{key}")
                    else:
                        print(f"[err]  [read_cdf]  chxh is not json:  [type]: {type(res_a)}, [data]: {res_a}")
        except Exception as e:
            print(f"[err] [open] [{path_cfg_cpxh} {str(e)}]")
    else:
        print(f"file is not exists {path_cfg_cpxh}")
    #print(f"data of cfg_cpxh: {ret_json}")
    return ret_json
    

def getocrs(cgxh):
    ocrli = []
    for x in cgxh:
        if 'ocr' in cgxh[x]:
            ocrli += cgxh[x]['ocr']
    return ocrli


def check_ocr(cgxh, jixing, out3):
    ends = []
    if jixing not in cgxh:
        ends.append(f'没配置{jixing}')
        return ends

    aa = cgxh[jixing]
    if 'ocr' in aa and len(aa['ocr'])>0:
        ocr = aa['ocr']
        ocr_ok = {}
        allocrs = getocrs(cgxh)
        for x in ocr:
            ocr_ok[x] = 0
        for i, x in enumerate(out3):
            x = list(x)
            t, d = find_min_eddist(x[1], allocrs)
            if t in ocr_ok and d<30:
                x[1] = t
                ocr_ok[t] += 1
            out3[i] = x
        
        for x in ocr_ok:
            if ocr_ok[x]==0:
                ends.append('机型错误')

    return ends